package com.ibiaoke.boss.service;

import com.ibiaoke.common.consts.CommonConsts;
import com.ibiaoke.common.exception.ServiceException;
import com.ibiaoke.common.utils.AssertUtils;
import com.ibiaoke.common.utils.MD5Utils;
import com.ibiaoke.common.utils.SmsUtil;
import com.ibiaoke.customer.dao.CustomerDao;
import com.ibiaoke.customer.entity.Customer;
import com.ibiaoke.customer.entity.CustomerExample;
import com.ibiaoke.customer.service.DepositService;
import com.ibiaoke.marketing.service.CouponReceiveService;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

/**
 * Created by biaoke on 2017/6/23.
 */
@Service
public class RegisterServiceImpl implements RegisterService {

    public static int MIN_PASSWORD_LENGTH = 6;
    private Logger logger = Logger.getLogger(this.getClass().getName());

    @Autowired
    private CustomerDao customerDao;
    @Autowired
    private CouponReceiveService couponReceiveService;
    @Autowired
    private DepositService depositService;

    @Override
    public void registerByMobile(String mobile, String code, String password) {
        SmsUtil.validateMobileCode(mobile,code);
        AssertUtils.notBlank(password, "密码不能为空");
        AssertUtils.requireTrue(password.length() < MIN_PASSWORD_LENGTH, "密码长度不能小于6");

        CustomerExample customerExample = new CustomerExample();
        customerExample.createCriteria().andCustomerMobileEqualTo(mobile);
        if(customerDao.countByExample(customerExample)>0){
            throw new ServiceException("您的手机已注册");
        }
        createNewCustomer(mobile, password);
    }

    @Override
    public void createNewCustomer(String mobile, String password) {
        Customer customer = new Customer();
        customer.setCustomerMobile(mobile);
        customer.setUserSalt(UUID.randomUUID().toString());
        if (StringUtils.isNotEmpty(password)) {
            customer.setCustomerPassword(MD5Utils.getMD5String(password, customer.getUserSalt()));
        }
        customer.setIsMobile(CommonConsts.YES);
        customer.setCustomerNickname("果"+mobile.substring(9,11));
        customer.setCreateTime(new Date());
        customerDao.insertSelective(customer);

        customer = customerDao.getByMobile(mobile);
        //couponReceiveService.receiveRegCoupon(customer.getCustomerId());
        depositService.createNewDeposit(customer.getCustomerId());
    }
}
